﻿#if NETSTANDARD2_0 || NETCOREAPP3_0
using Longbow.Cache;
using Microsoft.AspNetCore.Http;
#if NETSTANDARD2_0
using Newtonsoft.Json;
#else
using System.Text.Json;
#endif

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// CacheManagerCorsHandler 中间件扩展类，负责解析 /CacheList.axd 请求
    /// </summary>
    public static class CacheManagerExtensions
    {
        /// <summary>
        /// 增加CacheManager跨站点管理中间件
        /// </summary>
        /// <param name="builder"></param>
        public static IApplicationBuilder UseCacheManager(this IApplicationBuilder builder)
        {
            return builder.MapWhen(context => context.Request.Path == "/CacheList.axd", app => app.Run(async context =>
            {
                var buffer = "[]";
                if (context.User.Identity.IsAuthenticated)
                {
                    var cacheKey = context.Request.Query.ContainsKey("cacheKey") ? context.Request.Query["cacheKey"].ToString() : string.Empty;
                    if (cacheKey == "*")
                    {
                        CacheManager.Clear();
                    }
                    else
                    {
                        // cacheKey = "Key1|Key2|Key3"
                        if (!string.IsNullOrEmpty(cacheKey)) CacheManager.Clear(cacheKey.Split('|'));
#if NETSTANDARD2_0
                        buffer = JsonConvert.SerializeObject(CacheManager.ToList());
#else
                        buffer = JsonSerializer.Serialize(CacheManager.ToList());
#endif
                    }
                }
                context.Response.Headers.Add("Content-Type", new Microsoft.Extensions.Primitives.StringValues("application/json; charset=utf-8"));
                await context.Response.WriteAsync(buffer);
            }));
        }
    }
}
#endif
